package com.dongdongshop.shiro;

import com.dongdongshop.util.JwtUtil;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //实例化shiro过滤器工厂
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        Map<String, String> map = new LinkedHashMap<>();//LinkedHashMap-->指可以按照存值的顺序取值, 存取有序
        //直接放过的路径
        map.put("/login/**", "anon");
        map.put("/sellerLogin/**", "anon");
        //退出登录
        map.put("/logout", "logout");
        //登录就能获取的权限(放在最后)
        map.put("/**", "authc");
        factoryBean.setFilterChainDefinitionMap(map);//设置过滤器链
        factoryBean.setSecurityManager(securityManager);//设置安全管理器  实例化参数SecurityManager
        factoryBean.setLoginUrl("/user/toLogin");//设置登录路径
        factoryBean.setUnauthorizedUrl("/user/unauthorized");//当我们访问到没有权限访问的url时, shiro默认跳转至提示页面
        return factoryBean;
    }

    //实例化参数SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联登录逻辑
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //实例化自定义的登录逻辑loginRealm
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }


    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");//加密的方法
        matcher.setHashIterations(10);//迭代的次数
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }
    @Bean
    public JwtUtil jwtUtil(){
        return new JwtUtil();
    }

}
